//
//  XrDataParse.m
//  TasteEnjoy
//
//  Created by XuRui on 16/4/19.
//  Copyright © 2016年 XuRui. All rights reserved.
//

#import "XrDataParse.h"
#import "AFNetworking.h"
#import "AppDelegate.h"

@implementation XrDataParse

#pragma mark - ------------ get请求 ---------------

+ (void)GETWithURL:(NSString *)urlStr par:(NSDictionary *)dic success:(void (^)(id))response filed:(void (^)(NSError *))err
{
    AppDelegate *app = [[UIApplication sharedApplication] delegate];

    //转圈类
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:app.window animated:YES];
    hud.labelText =  @"Please Wait a Moment";
    
    hud.labelColor = [UIColor whiteColor];
    hud.color = [UIColor lightGrayColor];
    
    
    AFHTTPSessionManager *man = [AFHTTPSessionManager manager];
    // 有的返回的数据格式，AFN不支持解析，所以我们要设置一下。让AFN支持。
    [man.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
   
    //不在这中文转码
   // urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
   // urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:urlStr]];
 
    
    //分区头 enjoy网址 Authorization: OAuth2 2.4cLpMIzH000q0Z5066dffa180c6pc2
    [man.requestSerializer setValue:@"OAuth2 2.4cLpMIzH000q0Z5066dffa180c6pc2" forHTTPHeaderField:@"Authorization"];
    
    //无网hash缓存
    NSString *path = [NSString stringWithFormat:@"%ld", (unsigned long)[urlStr hash]];
    //建沙盒路径 yes 绝对路径
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:path];
    
    
    [man GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //归档
        [NSKeyedArchiver archiveRootObject:responseObject toFile:filePath];
        
        response(responseObject);
 

        [hud hide:YES]; /**< 移除转圈类 */

        
        //隐藏
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //解档
        id result = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
        
        response(result);
    
        err(error);
        [hud hide:YES afterDelay:0.02];
        
        
    }];
}



+ (void)POSTWithURL:(NSString *)urlStr
                par:(NSDictionary *)dic
            success:(void (^)(id))response filed:(void (^)(NSError *))err
{
    
    
    AFHTTPSessionManager *man = [AFHTTPSessionManager manager];
    
    [man.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
    
    
    [man.requestSerializer setValue:@"version" forHTTPHeaderField:@"609"];

    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [man POST:urlStr parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        response(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        err(error);
        
    }];
    
}



#if 0
#pragma mark - ------------ get ---------------
+ (void)getUrl:(NSString *)url
          body:(id)body
      response:(ResposeStyle)style
requestHeadFile:(NSDictionary *)handFile
       success:(void (^)(NSURLSessionDataTask *task, id resposeObject))success
       failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
    
    /* 1. 获取单例的网络管理对象 */
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    /* 2. 根据style的类型, 去选择返回值类型 */
    switch (style) {
        case JSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case XML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case Data:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        default:
            break;
    }
    
    // 3. 设置响应数据支持类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript", nil]];
    
    /* 4. 给网络请求添加请求头 */
    if (handFile) {
        for (NSString *key in handFile.allKeys) {
            [manager.requestSerializer setValue:handFile[key] forHTTPHeaderField:key];
        }
    }
    
    /* 5. UTF8转码 */
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    /* 6. 发送get请求 */
    [manager GET:url parameters:body progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(task, responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure)           {
            failure(task, error);
        }
    }];
    
}


#pragma mark - ------------ post ---------------

+ (void)postUrlString:(NSString *)url
                 body:(id)body
             response:(ResposeStyle)style
            bodyStyle:(RequestStyle)bodyStyle
      requestHeadFile:(NSDictionary *)headFile
              success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
              failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
    // 1.获取Session管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 2.设置网络请求返回时, responseObject的数据类型
    switch (style) {
        case JSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case XML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case Data:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        default:
            break;
    }
    // 3.判断body体的类型
    switch (bodyStyle) {
        case RequestJSON:
            // 以JSON格式发送
            manager.requestSerializer = [AFHTTPRequestSerializer serializer];
            break;
        case RequestString:
            // 保持字符串样式
            [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, id parameters, NSError *__autoreleasing *error) {
                return parameters;
            }];
        case RequestDefault:
            // 默认情况会把JSON拼接成字符串, 但是没有顺序
            break;
            
        default:
            break;
    }
    // 4.给网络请求加请求头
    if (headFile) {
        for (NSString *key in headFile) {
            [manager.requestSerializer setValue:headFile[key] forHTTPHeaderField:key];
        }
    }
    // 5.设置支持的响应头格式
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript", nil]];
    // 6.发送网络请求
    [manager POST:url parameters:body progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(task, responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(task, error);
        }
    }];
    
    
    
}

#endif

@end
